from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from starlette.endpoints import WebSocketEndpoint


class ConnectionManager:
    def __init__(self):
        # 保存当前所有的链接的websocket对象
        # self.active_connections: List[WebSocket] = []
        self.active_connections = []

    async def connect(self, websocket: WebSocket):
        client = str(websocket)[1:-1].split(' ')[3]
        print("是后端还是兑换", client)
        await websocket.accept()
        # 添加到当前已链接成功的队列中进行管理
        self.active_connections.append(websocket)

    async def close(self, websocket: WebSocket):
        # 主动的断开的客户端的链接，不是抛出异常的方式断开
        await websocket.close()
        self.active_connections.remove(websocket)

    async def disconnect(self, websocket: WebSocket):
        # 从队列里面删除我们的已经断开链接的websocket对象
        self.active_connections.remove(websocket)
        # await websocket.close()

    async def send_personal_message(self, message: str, websocket: WebSocket):
        # 发现消息
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        # 循环变量给所有在线激活的链接发送消息-全局广播
        print("当前的用户链接数，", len(self.active_connections))
        for connection in self.active_connections:
            await connection.send_text(message)
